package com.lin.fengxiu.repository;

import com.lin.fengxiu.model.Sku;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @ClassName SkuRepository
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/4/3 11:53
 * @Version 1.0
 */
public interface SkuRepository extends JpaRepository<Sku, Long> {

    /**
     * @Description TODO 根据一组SKUID 查询SKU
     * @param ids
     * @return
     */
    List<Sku> findAllByIdIn(List<Long> ids);

    /**
     * @Description TODO 从乐观锁的角度进行减库存，避免超卖
     * @param sid
     * @param quantity
     * @return
     */
    @Modifying
    @Query("update Sku s \n" +
            "set s.stock = s.stock - :quantity\n" +
            "where s.id = :sid\n" +
            "and s.stock >= :quantity")
    int reduceStock(@Param("sid") Long sid,@Param("quantity") Long quantity);

    @Modifying
    @Query("update Sku s set s.stock=s.stock+(:quantity) where s.id = :sid")
    int recoverStock(@Param("sid") Long sid, @Param("quantity") Long quantity);
}
